<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 新增商品
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form
        ref="formValidate2"
        :model="bloc.model"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding:50px 10% 0 10%;width: 860px"
      >
        <FormItem label="商品型号:" prop="modelId" required>
          <i-select v-model="bloc.model.modelId" filterable style="width: 400px">
            <i-option v-for="item in bloc.modeList" :value="item.id" :key="item.id">{{ item.name }}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="商品品号:" prop="colorId" required>
          <i-select v-model="bloc.model.colorId" filterable style="width: 400px">
            <i-option v-for="item in bloc.colorList" :value="item.id" :key="item.id">{{ item.name }}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="商品标价:" prop="price" required>
          <Input v-model="bloc.model.price"  style="width: 400px" type="number"/>
        </FormItem>
        <FormItem label="商品分类:" prop="categoryId" required>
          <i-select v-model="bloc.model.categoryId" filterable style="width: 400px">
            <i-option v-for="item in bloc.sortList" :value="item.id" :key="item.id">{{ item.sortName }}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="最大积分抵扣上限:" prop="point" required>
          <Input v-model="bloc.model.point"  style="width: 400px" type="number"/>
        </FormItem>
        <FormItem label="商品轮播图:" prop="banners" required>
          <div class="demo-upload-list" v-for="(item, index) in posterFileList" :key="index">
            <template v-if="item.status === 'finished'">
              <img :src="item.modelIcon">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="posterHandleView(item.modelIcon)"></Icon>
                <Icon type="ios-trash-outline" @click.native="posterHandleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="4000"
            :format="['jpg','png']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="posterHandleMaxSize1"
            :on-success="posterHandleSuccess"
            type="drag"
            multiple
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="posterVisible">
              <img :src="posterUrl" v-if="posterVisible" style="width: 100%">
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于2M</p>
        </FormItem>
        <FormItem label="商品详情图:" prop="detail" required>
          <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
            <template v-if="item.status === 'finished'">
              <img :src="item.modelIcon">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.modelIcon)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="50"
            :format="['jpg','png']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-success="handleSuccess"
            type="drag"
            multiple
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%">
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG 格式，图片小于50k</p>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <AppButton
          ref="save"
          style="margin-left: 30px;width: 100px;height: 40px;"
          type="primary"
          :disabled="bloc.isDetail"
          @click="addModel('formValidate2')"
        >保存
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import {store} from '@/store/Store';
    import {baseUrl} from '@/base/Request';
    import {Route} from 'vue-router';
    import {FormBloc} from './FormBloc';
    import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
    import {AppButton} from '@/type/AppButton';

    @Component({
        components: {CompanySeletorSingle}
    })

    export default class extends Vue {
        disabled: boolean = true;

        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next(vm => {
                if (vm.$route.query.sortId === 'undefined') {
                    vm.disabled = false
                }
                vm.bloc.sortId = Number(vm.$route.query.sortId);
                vm.bloc.model.categoryId = vm.bloc.sortId;
                vm.bloc.getAllCategory(1, 1000, 'ASC');
                vm.bloc.getAllModel(1, 1000, 'ASC');
                vm.bloc.getAllColor(1, 1000, 'ASC');
            });
        }

        bloc = new FormBloc();

        get uploadHeaders() {
            return {
                'Authorization': 'Bearer ' + store.state.auth.accessToken
            }
        };

        get uploadAction() {
            return `${baseUrl}/api/upload/image`
        }

        imgUrl = '';
        posterUrl = '';
        visible = false;
        posterVisible = false;

        get fileList() {
            return this.bloc.fileList.map(x => {
                return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
            });
        }

        get posterFileList() {
            return this.bloc.posterFileList.map(x => {
                return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
            });
        }

        handleView(url) {
            this.imgUrl = url;
            this.visible = true;
        }

        posterHandleView(url) {
            this.imgUrl = url;
            this.visible = true;
        }

        handleRemove(file) {
            this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
        }

        posterHandleRemove(file) {
            this.bloc.posterFileList.splice(this.bloc.posterFileList.indexOf(file), 1);
        }

        ruleValidate3: any = {
            modelId: [{required: true, message: '商品型号不能为空', trigger: 'blur'}],
            colorId: [{required: true, message: '商品品号不能为空', trigger: 'blur'}],
            price: [{required: true, message: '商品标价不能为空', trigger: 'change', type: 'number'}],
            point: [{required: true, message: '最大抵扣积分不能为空', trigger: 'change', type: 'number'}],
            categoryId: [{required: true, message: '商品分类不能为空', trigger: 'blur'}]
        };
        $refs!: {
            save: AppButton
            formValidate2: HTMLFormElement
        };

        // 添加产品
        addModel(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.$refs.save.bloc.loading = true;
                    this.bloc.addModel(this.bloc.model).then(res => {
                        this.$Message.success('保存成功');
                        this.$refs.save.bloc.loading = false;
                        this.$router.push({path: '/product', query: {sortId: this.bloc.sortId + ''}});
                    }).catch(err => {
                        // this.$Message.error('保存失败');
                        this.$Message.error(err.message);
                    }).finally(() => {
                        this.$refs.save.bloc.loading = false;
                    })
                }
            });
        }

        handleFormatError1(file) {
            this.$Message.error('请选择格式为JPG、PNG格式的文件')
        }

        handleMaxSize1(file) {
            this.$Message.error('图片大小不能超过50k')
        }

        posterHandleMaxSize1(file) {
            this.$Message.error('图片大小不能超过2M')
        }

        handleSuccess(res, file) {
            this.bloc.model.modelIcon = res.data[0];
            if (this.bloc.fileList.length > 0) {
                this.bloc.fileList = []
            }
            this.bloc.fileList.push(this.bloc.model.detail)
        }

        posterHandleSuccess(res, file) {
            this.bloc.model.poster = res.data[0];
            // if (this.bloc.posterFileList.length > 0) {
            //     this.bloc.posterFileList = []
            // }
            this.bloc.posterFileList.push(this.bloc.model.banners)
        }

        handleCancel() {
            this.$router.push({path: `/product`, query: {sortId: this.bloc.sortId + ''}});
        }
    }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    display: flex !important;
    justify-content: start !important;
    align-items: center !important;
  }
</style>
